/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use props file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ref, onMounted, SetupContext } from 'vue';
import { DropdownProps } from '../../types';

export function useDropdown(props: DropdownProps, context: SetupContext) {

    let menu: any;
    const show = ref(props.show);
    onMounted(() => {
        menu = document.querySelector('.dropdown-menu');
    });

    /** 点击元素之外  列表项消失 */
    const closeDropMenu = () => {
        if (props.hover) {
            return;
        }
        show.value = false;
        // context.emit('visibleChange');
        // 解除事件绑定
        document.removeEventListener('click', closeDropMenu);
        menu.removeEventListener('click', closeDropMenu);
        document.removeEventListener('scroll', closeDropMenu);
        menu.removeEventListener('scroll', closeDropMenu);
    };

    /** 点击列表项显示与否 */
    const showDropMenu = (e?: Event) => {
        if (props.hover || props.disabled) {
            return;
        }
        e?.stopPropagation();
        show.value = !show.value;
        // context.emit('visibleChange');
        document.addEventListener('click', closeDropMenu);
        document.addEventListener('scroll', closeDropMenu);
        if (!props.hideOnClick) {
            menu.addEventListener('click', (event: any) => {
                event.stopPropagation();
            });
            menu.addEventListener('scroll', (event: any) => {
                event.stopPropagation();
            });
        }
    };
    /** 弹出事件 */
    const selectItem = (model: any) => {
        context.emit('select', model);
    };

    /** hover 实现 */
    const hoverDropdown = () => {
        if (!props.hover) {
            return;
        }
        show.value = !show.value;
        // context.emit('visibleChange');
    };

    const leftButtonClick = () => {
        // context.emit('leftClick');
    };
    const resolveSize = (size: any) => {
        const regex = /px|em|rem|pt|%/;
        // 说明是字符串
        return regex.test(size)
            ? `${parseInt(size, 10)}${size.match(regex)[0]}`
            : `${size}px`;
    };
    return {
        show,
        showDropMenu,
        hoverDropdown,
        leftButtonClick,
        closeDropMenu,
        selectItem,
        resolveSize
    };
}
